<script setup lang="ts">
import type { ILoginRequest } from '@fl/api/iam-api'
import type { FormInstance, FormRules } from 'element-plus'
import { jointLogin, userLogin } from '@fl/api/joint-api/login'
import { SubmitBtn } from '@fl/components'
import { encrypt } from '@/utils/SM4'
import { ElForm, ElFormItem } from 'element-plus'
import { getJointAppKey, getJointToken, setJointToken } from '@fl/logics/jointAuth'
import { cookieClear, setIAMToken } from '@fl/logics/authentication'
import { useUserStore } from '@/store/user'

import { useUserStoreWithOut } from '@fl/store/modules/user'
import { setRoutesByRole } from '@/router/helper'
import { jointHttp } from '@fl/axios'
import { useJointStoreWithOut } from '@fl/store/modules/joint'

type IForm = Pick<ILoginRequest, 'password' | 'username'>

const ruleFormRef = ref<FormInstance>()

const ruleForm = reactive<IForm>({
    password: '',
    username: '',
})

const rules = reactive<FormRules<IForm>>({
    password: [
        {
            message: '请输入密码',
            required: true,
        },
    ],
    username: [
        {
            message: '请输入用户名',
            required: true,
        },
    ],
})

const { isPending, mutateAsync } = useMutation({
    // mutationFn: (data: ILoginRequest) => _rOauthToken2(data),
    mutationFn: (data: ILoginRequest) => jointLogin(data),
    mutationKey: ['jointLogin'],
    onSuccess: async (data) => {
        // console.log('🚀 ~ userLogin ~ data:', data)
        data && setJointToken(data?.iamToken)
        jointHttp.setHeader({ 'iam-token': data?.iamToken })
        const userStore = useUserStoreWithOut()
        const result = { ...data, iamAccountVo: data?.myAccountVo?.iamAccountVo }
        window.sessionStorage.setItem('USER_ID', data.myAccountVo?.iamAccountVo?.id)

        result.name = data?.myAccountVo?.iamAccountVo?.username
        userStore.setUserInfo(result)

        // 获取联合运营应用的appkey等信息,有些地方会拼接联合运营的卡片
        const jointCard = data?.myAccountVo?.iamAccountVo?.appRoles?.find((item: any) => item.appName?.includes('联合运营'))
        if (jointCard?.appKey) {
            const { appId, appKey, appName } = jointCard
            console.log('🚀 ~ onSuccess: ~ jointCard:', { appId, appKey, appName })
            const jointStore = useJointStoreWithOut()
            jointStore.setJointCardInfo({ appId, appKey, appName })
        }

        await setRoutesByRole(data)
    },
    onError: (error) => {
        console.error('登录失败', error)
    },
})

async function submitForm(formEl: FormInstance | undefined) {
    if (!formEl)
        return

    const isValid = await formEl.validate()
    if (!isValid) {
        return false
    }

    mutateAsync({
        username: ruleForm.username,
        password: encrypt(ruleForm.password),
    })
}
onMounted(() => {
    window.localStorage.clear()
    window.sessionStorage.clear()
    cookieClear()
})
</script>

<template>
    <ElForm ref="ruleFormRef"
            label-position="top"
            :model="ruleForm"
            :rules="rules"
            @submit.prevent
    >
        <div class="mb-16 flex flex-col gap-12">
            <ElFormItem label="用户名"
                        prop="username"
            >
                <el-input v-model="ruleForm.username"
                          placeholder="请输入用户名"
                          maxlength="20"
                          size="large"
                />
            </ElFormItem>
        </div>

        <div class="flex flex-col gap-12">
            <ElFormItem label="密码"
                        prop="password"
            >
                <el-input v-model="ruleForm.password"
                          type="password"
                          show-password
                          maxlength="20"
                          placeholder="请输入密码"
                          size="large"
                />
            </ElFormItem>
        </div>

        <ElFormItem>
            <SubmitBtn type="primary"
                       native-type="submit"
                       class="mt-30 rounded-3 text-#fff lh-48 text-center w-full cursor-pointer"
                       size="large"
                       :loading="isPending"
                       @click="submitForm(ruleFormRef)"
            >
                登录
            </SubmitBtn>
        </ElFormItem>
    </ElForm>
</template>
